<?php
ob_start();
### supporting WP2.6 wp-load & custom wp-content / plugin dir

if ( file_exists( ABSPATH . 'wp-load.php') )
	require_once( ABSPATH . 'wp-load.php' );
else
	require_once( ABSPATH . 'wp-config.php' );

if( !current_user_can('track_cforms') )
	wp_die("access restricted.");

global $wpdb;

$wpdb->cformssubmissions	= $wpdb->prefix . 'cformssubmissions';
$wpdb->cformsdata       	= $wpdb->prefix . 'cformsdata';

### new global settings container, will eventually be the only one!
$cformsSettings = get_option('cforms_settings');

$page = $_POST['page'];
$rp = $_POST['rp'];
$sortname = $_POST['sortname'];
$sortorder = $_POST['sortorder'];

$qtype = $_POST['qtype'];
$query = $_POST['query'];

### get form id from name
$query = str_replace('*','',$query);
$form_ids = false;
if ( $qtype == 'form_id' && $query <> '' ){

	$forms = $cformsSettings['global']['cforms_formcount'];

	for ($i=0;$i<$forms;$i++) {
		$no = ($i==0)?'':($i+1);

		if ( preg_match( '/'.$query.'/i', $cformsSettings['form'.$no]['cforms'.$no.'_fname'] ) ){
        	$form_ids = $form_ids . "'$no',";
		}
	}
	$querystr = ( !$form_ids )?'$%&/':' form_id IN ('.substr($form_ids,0,-1).')';
}else{
	$querystr = '%'.$query.'%';
}


if ( $form_ids )
	$where = "WHERE $querystr";
elseif ( $query<>'' )
	$where = "WHERE $qtype LIKE '$querystr'";
else
	$where = '';

if (!$sortname)
	$sortname = 'id';
if (!$sortorder) $sortorder = 'desc';
	$sort = "ORDER BY $sortname $sortorder";
if (!$page)
	$page = 1;
if (!$rp)
	$rp = 10;

$start = (($page-1) * $rp);
$limit = "LIMIT $start, $rp";

for ($i=1; $i <= $cformsSettings['global']['cforms_formcount']; $i++){
	$n = ( $i==1 )?'':$i;
	$fnames[$i]=stripslashes($cformsSettings['form'.$n]['cforms'.$n.'_fname']);
}

function generate_xml_from_array($array, $node_name) {
$xml = '';
if (is_array($array) || is_object($array)) {
foreach ($array as $key=>$value) {
if (is_numeric($key)) {
$key = $node_name;
}
$xml .= '<' . $key . '>' . "\n" . generate_xml_from_array($value, $node_name) . '</' . $key . '><!--' . $key . '-->' . "\n";
}
} else {
$xml = htmlspecialchars($array, ENT_QUOTES) . "\n";
}
return $xml;
}



function generate_valid_xml_from_array($array, $node_block='rows', $node_name='node') {
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
header("Cache-Control: no-cache, must-revalidate" );
header("Pragma: no-cache" );
header("Content-type: text/xml");
$xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
$xml .= '<' . $node_block . '>' . "\n";
$xml .= "<page>1</page>";
$xml .= "<total>3</total>";
$xml .= generate_xml_from_array($array, $node_name);
$xml .= '<!--' . $node_block . '--></' . $node_block . '><' . "\n";
return $xml;
}
 
### get data from API
$array = get_cforms_entries( );
$xml = generate_valid_xml_from_array($array);



ob_end_clean();
echo $xml;
?>